<template>
	<a-form :ref="'ruleForm'" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
		<a-collapse ghost v-model:activeKey="activeKey">
			<a-collapse-panel key="1" header="数据配置">
				<a-row :gutter="[10, 10]">
					<a-col :span="24">
						<a-radio-group
							v-model:value="formState.dataSetConfig.dataSetType"
							optionType="button"
							buttonStyle="solid"
							:options="[
								{ label: '静态', value: 0 },
								{ label: '数据源', value: 1 }
							]"
						>
						</a-radio-group>
					</a-col>
					<a-col :span="24" v-if="formState.dataSetConfig.dataSetType == 0">
						<a-form-item label="百分比值">
							<a-input-number
								v-model:value="formState.percent.value"
								:min="0"
								:max="1"
								:step="0.01"
								style="width: 100%"
							/>
						</a-form-item>
					</a-col>
					<template v-else>
						<a-col :span="24">
							<SelectTree @onChange="selectTreeChange" v-model:paramsJson="formState.dataSetConfig.dataSetJson" />
						</a-col>
						<a-col :span="24">
							<a-form-item label="百分比字段" class="form-item">
								<a-select
									v-model:value="formState.percent.field"
									placeholder="请选择百分比字段"
									:options="fieldOptions"
									@change="() => getDataSourceFields()"
								></a-select>
							</a-form-item>
						</a-col>
					</template>
				</a-row>
			</a-collapse-panel>
		</a-collapse>
	</a-form>
</template>

<script setup>
	import config from '../config'
	import { defineEmits, defineExpose, defineProps, reactive, ref, watch } from 'vue'
	import { cloneDeep } from 'lodash-es'
	import { designStore } from '@/views/plugin/dashboard/store'
	import SelectTree from '@/views/plugin/dashboard/plugin/public/SelectTree/SelectTree.vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'

	const useDesignStore = designStore()
	const emits = defineEmits(['upDataConfig'])
	const activeKey = ref(['1'])

	const props = defineProps({
		config: {
			type: Object,
			default: () => {
				return cloneDeep(config)
			}
		}
	})

	// 创建本地配置缓存，用于存储用户修改但尚未确认的配置
	const localConfig = reactive(cloneDeep(props.config))

	// 表单状态使用本地配置
	const formState = reactive(cloneDeep(localConfig))
	// 数据变化清空下拉
	const selectTreeChange = () => {
		formState.percent.field = undefined
	}
	// 保存配置到父组件
	const saveConfig = () => {
		emits('upDataConfig', cloneDeep({ ...localConfig, ...formState }))
	}

	// 重置配置
	const resetConfig = () => {
		Object.assign(localConfig, cloneDeep(props.config))
		// 更新表单状态
		Object.assign(formState, cloneDeep(localConfig))
	}

	// 监听表单状态变化，更新本地配置
	watch(
		() => formState,
		(val) => {
			// 更新本地配置，但不触发事件
			Object.assign(localConfig, cloneDeep(val))

			// 更新预览配置（这会立即反映在预览区域）
			emits('upDataConfig', cloneDeep(localConfig))
		},
		{ deep: true }
	)

	// 数据源字段列表
	const fieldOptions = ref([])

	// 获取数据源字段
	const getDataSourceFields = () => {
		if (formState.dataSetConfig.dataSetType === 1 && formState.dataSetConfig.dataSetJson) {
			const list = useDesignStore.dataSource || []
			let datasetId = ''
			let indicatorId = ''
			list.forEach((parent) => {
				parent.config.indicators.forEach((child) => {
					if (child.id === formState.dataSetConfig.dataSetJson.id) {
						datasetId = parent.id
						indicatorId = child.id
					}
				})
			})
			if (datasetId && indicatorId) {
				// 下拉数据
				datasetApi.querySelectedColumns({ datasetId, indicatorId }).then((res) => {
					// 将返回的字段转换为下拉选项格式
					const fields = (res || []).map((field) => ({
						label: field,
						value: field
					}))
					fieldOptions.value = fields
				})
			}
		}
	}

	// 监听数据源变化
	watch(
		() => formState.dataSetConfig.dataSetJson,
		() => {
			getDataSourceFields()
		},
		{ deep: true }
	)

	// 初始化时获取字段
	watch(
		() => formState.dataSetConfig.dataSetType,
		(newVal) => {
			if (newVal === 1) {
				getDataSourceFields()
			}
		},
		{ immediate: true }
	)

	// 暴露方法给父组件
	defineExpose({
		saveConfig,
		resetConfig
	})
</script>

<style scoped>
	.form-item {
		margin-bottom: 0;
	}
	:deep(.ant-radio-button-wrapper) {
		padding: 0px;
		width: 100%;
	}
	:deep(.ant-radio-group) {
		display: flex;
		text-align: center;
	}
	:deep(.form-item) {
		margin-bottom: 0px;
	}
</style>
